<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import router from '@/router'
const task = ref([''])
const val = ref('')
function addTask() {
    task.value.push(val.value)
    sessionStorage.setItem('task', JSON.stringify(task.value))
    console.log(task.value)
}


function delTask(event: Event) {
    const target = event.target as HTMLElement | null;
    if (target !== null) {
        const son = target.parentNode?.parentNode?.parentNode as HTMLElement | undefined;
        if (son && son.parentNode) {
            const children = Array.from(son.parentNode.children as HTMLCollection);
            const index = children.indexOf(son);

            task.value.splice(index + 1, 1)
            sessionStorage.setItem('task', JSON.stringify(task.value))
        }
    }
}

function changeTask(event: Event) {
    const target = event.target as HTMLElement | null;
    if (target !== null) {
        const son = target.parentNode?.parentNode?.parentNode as HTMLElement | undefined;
        if (son && son.parentElement) {
            const children = Array.from(son.parentElement.children as HTMLCollection);
            const index = children.indexOf(son);
            const newTask = prompt('请输入新的任务内容')
            if (newTask !== null) {
                task.value[index + 1] = newTask
            }
            sessionStorage.setItem('task', JSON.stringify(task.value))
        }
    }
}

onMounted(() => {
    const tasks = sessionStorage.getItem('task')
    if (tasks !== null) {
        task.value = JSON.parse(tasks)
    }
})
</script>

<template>
    <el-container style="position: relative;;left: 45%;">
        
        <el-header>
            <van-button type="primary" @click="router.push('/home')" style="margin-bottom: 20px;">返回</van-button>
        </el-header>

        <el-container>
            <el-input placeholder="add task please" v-model="val"></el-input>
            <el-button @click="addTask()"> add</el-button>
        </el-container>
        <el-card style="max-width: 680px;height: 480px;">
            <template #header>
                <h3 style="margin: 0px;">以下是你的任务：</h3>
            </template>
            <div style="height: 250px;overflow-y: auto;">
                <div v-for="item in task.slice(1)">
                    <div style="width: 250px;height: 45px;display: flex;justify-content: space-between;">
                        <div style="max-width: 50px; overflow-x: auto;"> {{ item }}</div>
                        <div>
                            <el-button style="margin: 0px;" id="change" @click="changeTask($event)">change</el-button>
                            <el-button id="del" style="margin: 0px;" @click="delTask($event)">delete</el-button>
                        </div>
                    </div>
                </div>

            </div>

            <template #footer>
                <h3>你还有{{ task.length - 1 }}个任务需要完成！</h3>
            </template>

        </el-card>
    </el-container>

</template>